package com.changgou.system.goods.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changgou.common.constants.SpuConstants;
import com.changgou.goods.pojo.*;
import com.changgou.system.goods.dao.*;
import com.changgou.system.goods.service.SpuService;
import com.changgou.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Override
    @Transactional
    public void add(Goods goods) {
        Spu spu = goods.getSpu();
        spu.setId(Convert.toStr(idWorker.nextId()));
        spu.setStatus(SpuConstants.SPU_STATUS_NOT_CHECKED);
        spu.setIsDelete(SpuConstants.SPU_NOT_DELETE);
        spu.setIsMarketable(SpuConstants.SPU_NOT_MARKETABLE);
        this.save(spu);
        this.saveSkuList(goods);
    }

    /**
     * 根据ID查询商品
     *
     * @param id
     * @return
     */
    public Goods findGoodsById(String id) {
        List<Sku> skuList = skuMapper.selectList(Wrappers.<Sku>lambdaQuery().eq(Sku::getSpuId, id));
        return Goods.builder().spu(this.getById(id)).skuList(skuList).build();
    }


    @Override
    public void update(Goods goods) {
        Spu spu = goods.getSpu();
        this.save(spu);
        skuMapper.delete(Wrappers.<Sku>lambdaQuery().eq(Sku::getSpuId, spu.getId()));
        saveSkuList(goods);//保存sku列表
    }

    @Override
    public void audit(String id) {
        Spu spu = this.getById(id);
        if (ObjectUtil.isEmpty(spu)) {
            throw new RuntimeException("当前商品不存在");
        }
        if (StrUtil.equals(spu.getIsDelete(), SpuConstants.SPU_DELETE)) {
            throw new RuntimeException("当前商品处于删除状态");
        }
        spu.setStatus(SpuConstants.SPU_DELETE);
        spu.setIsMarketable(SpuConstants.SPU_NOT_MARKETABLE);
        this.updateById(spu);
    }

    @Override
    public void pull(String id) {
        Spu spu = this.getById(id);
        if (ObjectUtil.isEmpty(spu)) {
            throw new RuntimeException("当前商品不存在");
        }
        if (StrUtil.equals(spu.getIsDelete(), SpuConstants.SPU_DELETE)) {
            throw new RuntimeException("当前商品处于删除状态");
        }
        spu.setIsMarketable(SpuConstants.SPU_NOT_MARKETABLE);
        this.updateById(spu);
    }

    @Override
    public void put(String id) {
        Spu spu = this.getById(id);
        if (!StrUtil.equals(spu.getId(), SpuConstants.SPU_STATUS_NOT_CHECKED)) {
            throw new RuntimeException("当前商品未审核通过");
        }
        spu.setIsMarketable(SpuConstants.SPU_MARKETABLE);
        this.updateById(spu);
    }

    @Override
    public void delById(String id) {
        Spu spu = this.getById(id);
        if (StrUtil.equals(spu.getIsMarketable(), SpuConstants.SPU_MARKETABLE)) {
            throw new RuntimeException("当前商品处于上架状态,无法删除");
        }
        spu.setIsDelete(SpuConstants.SPU_DELETE);
        spu.setStatus(SpuConstants.SPU_STATUS_NOT_CHECKED);
        this.updateById(spu);
    }

    @Override
    public void restore(String id) {
        Spu spu = this.getById(id);
        if (StrUtil.equals(spu.getIsDelete(), SpuConstants.SPU_NOT_DELETE)) {
            throw new RuntimeException("当前商品未删除");
        }
        spu.setIsDelete(SpuConstants.SPU_NOT_DELETE);
        spu.setStatus(SpuConstants.SPU_STATUS_NOT_CHECKED);
        this.updateById(spu);
    }

    @Override
    public void realDelete(String id) {
        Spu spu = this.getById(id);
        if (StrUtil.equals(spu.getIsDelete(), SpuConstants.SPU_NOT_DELETE)) {
            throw new RuntimeException("当前商品未删除");
        }
        this.removeById(spu);
    }

    private void saveSkuList(Goods goods) {
        Spu spu = goods.getSpu();
        Category category = categoryMapper.selectOne(Wrappers.<Category>lambdaQuery().eq(Category::getId, goods.getSpu().getCategory3Id()));
        Brand brand = brandMapper.selectOne(Wrappers.<Brand>lambdaQuery().eq(Brand::getId, goods.getSpu().getBrandId()));

        CategoryBrand categoryBrand = CategoryBrand.builder()
                .brandId(spu.getBrandId())
                .categoryId(spu.getCategory3Id())
                .build();
        if (ObjectUtil.isNotEmpty(categoryBrandMapper.selectOne(Wrappers.<CategoryBrand>lambdaQuery()
                .eq(CategoryBrand::getBrandId, categoryBrand.getBrandId())
                .eq(CategoryBrand::getCategoryId, categoryBrand.getCategoryId())))) {
            categoryBrandMapper.insert(categoryBrand);
        }
        {
            categoryBrandMapper.insert(categoryBrand);
        }


        CollStreamUtil.toList(goods.getSkuList(), sku ->
                {
                    String name = spu.getName();
                    Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
                    specMap.forEach((k, v) -> sku.setSpec(StrUtil.format("{} {}", name, v)));
                    sku.setName(name);
                    sku.setSpuId(spu.getId());//设置spu的ID
                    sku.setCreateTime(new Date());//创建日期
                    sku.setUpdateTime(new Date());//修改日期
                    sku.setCategoryId(category.getId());//商品分类ID
                    sku.setCategoryName(category.getName());//商品分类名称
                    sku.setBrandName(brand.getName());//品牌名称
                    skuMapper.insert(sku);
                    return sku;
                }
        );
    }


}
